package com.spzx.common.rabbit.config;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 服务器启动时，执行rabbitTemplate初始化，设置确认函数和回退函数
 * ApplicationEvent      一些子事件的父类。
 * ApplicationReadyEvent 具体子事件。表示应用程序启动好，IOC容器初始化好，存在相关bean对象了。再进行相关的初始化。
 * 也可以使用相关的注解替代： @EventListener
 */
@Slf4j
@Component
public class RabbitInitConfigApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.setUpInitRabbitTemplete();
    }


    private void setUpInitRabbitTemplete() {
        //回调函数
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack){
                log.info("消息成功发送给交换机->" + correlationData);
            } else {
                retrySendMsg(correlationData);
                log.info("消息没有发送给交换机->" + correlationData);
            }
        });

        //回退函数
        rabbitTemplate.setReturnsCallback(returned -> {
            log.error("Returned: " + returned.getMessage() + "\nreplyCode: " + returned.getReplyCode()
                    + "\nreplyText: " + returned.getReplyText() + "\nexchange/rk: "
                    + returned.getExchange() + "/" + returned.getRoutingKey());

            //得到关联信息中存入的关联标识（id），通过id可从redis中取到关联数据
            String correlationId = returned.getMessage().getMessageProperties().getHeader("spring_returned_message_correlation");
            String correlationDataStr = (String) redisTemplate.opsForValue().get(correlationId);
            GuiguCorrelationData guiguCorrelationData = JSON.parseObject(correlationDataStr, GuiguCorrelationData.class);

            //重新发送
            retrySendMsg(guiguCorrelationData);
        });
    }

    //用于消息重发
    private void retrySendMsg(CorrelationData correlationData){
        //correlationData中携带的就是关联数据，把他转化为GuiguCorrelationData类型数据
        GuiguCorrelationData guiguCorrelationData = (GuiguCorrelationData) correlationData;

        int retryCount = guiguCorrelationData.getRetryCount(); //retryCount表示重发次数
        if (retryCount>=3){
            log.info("重发次数超过三次");
            return;
        }

        retryCount++;
        guiguCorrelationData.setRetryCount(retryCount);//次数加一，重新赋值

        //retryCount改变，重新写入redis中，共下次使用  重点：先存再发送
        redisTemplate.opsForValue().set(guiguCorrelationData.getId(),JSON.toJSONString(guiguCorrelationData),10, TimeUnit.SECONDS);

        //重新发送
        if (guiguCorrelationData.isDelay()){ //说明是延时队列
            rabbitTemplate.convertAndSend(guiguCorrelationData.getExchange(),
                    guiguCorrelationData.getRoutingKey(),
                    guiguCorrelationData.getMessage(),
                    message -> {
                        message.getMessageProperties().setDelay(guiguCorrelationData.getDelayTime()*1000);
                        return message;
                    },
                    guiguCorrelationData);
        } else {
            rabbitTemplate.convertAndSend(guiguCorrelationData.getExchange(),guiguCorrelationData.getRoutingKey(),guiguCorrelationData.getMessage(),guiguCorrelationData);
        }

    }


}
